package com.weixing.mall.core.config;

import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.support.task.ExceptionHandlingAsyncTaskExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/9/18 17:41
 * @Modified By:
 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncTaskExecutorConfig implements AsyncConfigurer {

    @Autowired
    private WeiXingProperties weiXingProperties;

    @Bean(name = "taskExecutor")
    @Override
    public Executor getAsyncExecutor() {
        log.info("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(weiXingProperties.getTask().getCorePoolSize());
        executor.setMaxPoolSize(weiXingProperties.getTask().getMaxPoolSize());
        executor.setQueueCapacity(weiXingProperties.getTask().getQueueCapacity());
        executor.setKeepAliveSeconds(weiXingProperties.getTask().getKeepAliveSeconds());
        executor.setThreadNamePrefix(weiXingProperties.getTask().getThreadNamePrefix());
        return new ExceptionHandlingAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}
